package org.example.myframework.frame.common.web.trace;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Component
@Slf4j
public class TraceIdFilter implements Filter {


    /**
     * 拦截所有请求，判断其他业务端是否有赋值TraceId，如果没有赋值，则手动赋值后放行
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String traceId = httpServletRequest.getHeader(TraceIdConstant.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
            traceId = TraceIdContext.generateTraceID();
        }
        TraceIdContext.setTraceID(traceId);
        filterChain.doFilter(servletRequest, servletResponse);
        TraceIdContext.clearTraceID();
    }
}
